package cn.ihelloworld.dao.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import cn.ihelloworld.bean.Article;
import cn.ihelloworld.bean.PageResult;
import cn.ihelloworld.dao.IArticleDao;
import cn.ihelloworld.dao.Pagation;
@Repository
public class ArticleDaoImpl implements IArticleDao {

	@Autowired
	private SessionFactory sf;
	
	@Override
	public Article get(String id) {
		return (Article)sf.getCurrentSession().get(Article.class,id);
	}

	@Override
	public List<Article> select(Article t) {
		List<Article> list=new ArrayList<Article>();
		if(t!=null){
			Criteria criteria=sf.getCurrentSession().createCriteria(Article.class);
			if(t.getId()!=null){
				criteria.add(Restrictions.eq("id", t.getId()));
			}
			if(t.getAuthor()!=null){
				criteria.add(Restrictions.ilike("author", t.getAuthor(),MatchMode.START));
			}
			if(t.getCatagory()!=null&&t.getCatagory().getCode()!=null){
				criteria.add(Restrictions.eq("catagory.code", t.getCatagory().getCode()));
			}
			if(t.getTag()!=null){
				criteria.add(Restrictions.like("tag", t.getTag(), MatchMode.ANYWHERE));
			}
			if(t.getTitle()!=null){
				criteria.add(Restrictions.like("title", t.getTitle(), MatchMode.START));;
			}
			list=criteria.list();
		}
		return list;
	}

	@Override
	public Pagation<Article> selectForPage(Article t, int currentPage,
			int pageSize) {
		Pagation<Article> pagation=new Pagation<Article>();
		int start=currentPage==0?0:(currentPage-1)*pageSize;
		int end=currentPage*pageSize;
		pagation.setStart(start);
		pagation.setEnd(end);
		List<Article> list=new ArrayList<Article>();
		if(t!=null){
			Criteria criteria=sf.getCurrentSession().createCriteria(Article.class);
			if(t.getId()!=null){
				criteria.add(Restrictions.eq("id", t.getId()));
			}
			if(t.getAuthor()!=null){
				criteria.add(Restrictions.eq("author", t.getAuthor()));
			}
			if(t.getCatagory()!=null&&t.getCatagory().getCode()!=null){
				criteria.add(Restrictions.eq("catagory.code", t.getCatagory().getCode()));
			}
			if(t.getTag()!=null){
				criteria.add(Restrictions.like("tag", t.getTag(), MatchMode.ANYWHERE));
			}
			if(t.getTitle()!=null){
				criteria.add(Restrictions.like("title", t.getTitle(), MatchMode.ANYWHERE));;
			}
			criteria.addOrder(Order.desc("createDate"));
			Long count=(Long) criteria.setProjection(Projections.rowCount()).uniqueResult();
			pagation.setTotal(count.intValue());
			criteria.setProjection(null);
			criteria.setFirstResult(start);
			criteria.setMaxResults(end);
			list=criteria.list();
		}
		pagation.setRs(list);
		return pagation;
	}

	@Override
	public void saveOrUpdate(Article t) {
		t.setCreateDate(new Date());
		sf.getCurrentSession().saveOrUpdate(t);
	}

	@Override
	public void delete(String id) {
		Article article=new Article();
		article.setId(id);
		sf.getCurrentSession().delete(article);
	}

	@Override
	public void delete(String[] ids) {
		StringBuffer sb=new StringBuffer("delete Article where id in");
		sb.append("(");
		for(int i=0;i<ids.length;i++){
			sb.append("'");
			sb.append(ids[i]);
			sb.append("'");
			if(i!=ids.length-1){
				sb.append(",");
			}
		}
		sb.append(")");
		sf.getCurrentSession().createQuery(sb.toString()).executeUpdate();
	}

	@Override
	public List<Article> selectLast(String catagoryId,int num) {
		Query query=sf.getCurrentSession().createQuery("select new Article(id,title,summary) from Article where catagory.code=? order by createDate desc");
		query.setString(0, catagoryId);
		query.setFirstResult(0);
		query.setMaxResults(num);
		return query.list();
	}

	@Override
	public List<Article> selectHot(String catagoryId, int num) {
		Query query=sf.getCurrentSession().createQuery("select new Article(id,title) from Article where catagory.code=? order by (readCount+commentCount) desc");
		query.setString(0, catagoryId);
		query.setFirstResult(0);
		query.setMaxResults(num);
		return query.list();
	}

	@Override
	public List<Article> selectHotByTag(String tag, int num) {
		Query query=sf.getCurrentSession().createQuery("select new Article(a.id,a.title,a.summary,c.code) from Article a,Catagory c where a.catagory.code=c.code and a.tag like ? order by (a.readCount+a.commentCount) desc");
		query.setString(0, "%"+tag+"%");
		query.setFirstResult(0);
		query.setMaxResults(num);
		return query.list();
	}

	@Override
	public List<Article> selectLastByTag(String tag, int num) {
		Query query=sf.getCurrentSession().createQuery("select new Article(a.id,a.title,a.summary,c.code) from Article a,Catagory c where a.catagory.code=c.code and a.tag like ? order by a.createDate desc");
		query.setString(0, "%"+tag+"%");
		query.setFirstResult(0);
		query.setMaxResults(num);
		return query.list();
	}

	@Override
	public void update(List<Article> list) {
		Query query=sf.getCurrentSession().createQuery("update Article set title=?,author=?,fromSite=?,catagory.id=? where id=?");
		for(Article article:list){
			query.setParameter(0,article.getTitle());
			query.setParameter(1,article.getAuthor());
			query.setParameter(2, article.getFromSite());
			query.setParameter(3, article.getCatagoryId());
			query.setParameter(4, article.getId());
			query.executeUpdate();
		}
	}

	@Override
	public List<Article> selectPreNext(String articleId) {
		Query query=sf.getCurrentSession().createQuery("select new Article(a.id,a.title,a.summary,c.code) from Article a,Catagory c where a.catagory.code=c.code and c.code=(select catagory.code from Article where id=?) and a.createDate < (select createDate from  Article where id=?) ");
		query.setString(0, articleId);
		query.setString(1, articleId);
		query.setFirstResult(0);
		query.setMaxResults(1);
		List list=query.list();
		if(list.size()==0){
			Article a=new Article();
			a.setTitle("没有了");
			list.add(a);
		}
		query=null;
		query=sf.getCurrentSession().createQuery("select new Article(a.id,a.title,a.summary,c.code) from Article a,Catagory c where a.catagory.code=c.code and c.code=(select catagory.code from Article where id=?) and a.createDate > (select createDate from  Article where id=?) ");
		query.setString(0, articleId);
		query.setString(1, articleId);
		query.setFirstResult(0);
		query.setMaxResults(1);
		List list2=query.list();
		if(list2.size()==0){
			Article a=new Article();
			a.setTitle("没有了");
			list2.add(a);
		}
		list.addAll(list2);
		return list;
	}

  @Override
  public PageResult<Article> selectByPage(String catagoryId,int page)
  {
    PageResult<Article> result=new PageResult<Article>();
    result.setCurrentPage(page);
    Query query=sf.getCurrentSession().createQuery("select count(id) from Article where catagory.code=?");
    query.setString(0, catagoryId);
    long count=(Long) query.list().get(0);
    int rowCount=(int) count;
    result.setRowCount(rowCount);
    int pageCount=rowCount%result.getPageSize()==0?rowCount/result.getPageSize():rowCount/result.getPageSize()+1;
    result.setPageCount(pageCount);
    
    query=sf.getCurrentSession().createQuery("select new Article(id,title,summary) from Article where catagory.code=? order by createDate desc");
    query.setString(0, catagoryId);
    query.setFirstResult((page-1)*result.getPageSize());
    query.setMaxResults(result.getPageSize());
    List<Article> list=query.list();
    result.setRows(query.list());
    return result;
  }

}
